package cn.wwcyc.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.wwcyc.domain.*;
import cn.wwcyc.exception.WWException;
import cn.wwcyc.exception.WWExceptionEnum;
import cn.wwcyc.mapper.TjUserroleMapper;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.wwcyc.service.UserService;
import cn.wwcyc.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* @author Administrator
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-07-01 12:08:41
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    TjUserroleMapper tjUserroleMapper;
    @Override
    //次函数有问题，请用下面的函数getUserRoleMenuVo，
    public IPage<UserRoleMenuVo> getUserRoleMenuVoPage(IPage<UserRoleMenuVo> page){

        page.setTotal(userMapper.selectCount(null));
        page.setPages(page.getTotal()%page.getSize() == 0 ? page.getTotal()/page.getSize() : page.getTotal()/page.getSize() + 1);

        List<UserRoleMenuVo> userRoleMenuVoList = userMapper.getUserRoleMenuVoPage(((page.getCurrent()-1)*page.getSize()), (page.getCurrent()*page.getSize()));

        page.setRecords(userRoleMenuVoList);
        return page;
    }
    @Override
    public User getCurrentUser(HttpServletRequest request){
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            throw new WWException(WWExceptionEnum.AUTHORITION_FAIL);
        }
        // 获取 token 中的 用户信息
        String userId = null;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new WWException(WWExceptionEnum.USER_NOT_EXISTED);
        }
        User user = getById(userId);
        if(user == null) {
            throw new WWException(WWExceptionEnum.USER_NOT_EXISTED);
        }
        return user;
    }


    @Override
    public IPage<UserRoleMenuVo> getUserRoleMenuVo(IPage<UserRoleMenuVo> page, String username, List<Long> dwIdList) {

        QueryWrapper<User> qw = new QueryWrapper<>();
        if(!StringUtils.isBlank(username)){
            qw.like("username", username);
        }
        if(dwIdList !=null && dwIdList.size()>0){
            qw.in("dw", dwIdList);
        }
        long count = userMapper.selectCount(qw);
        page.setTotal(count);
//        page.setTotal(userMapper.selectCount(null));
        page.setPages(page.getTotal()%page.getSize() == 0 ? page.getTotal()/page.getSize() : page.getTotal()/page.getSize() + 1);


        //查出所有数据
//        System.out.println("username is -------------"+username);
        List<UserRoleMenuVo> userRoleMenuVoList = userMapper.getUserRoleMenuVo(username, dwIdList);
//        System.out.println(userRoleMenuVoList);
        //获取分页数据
        List<UserRoleMenuVo> pageList = CollUtil.page((int)(page.getCurrent()-1), (int)page.getSize(), userRoleMenuVoList);

//        page.setRecords(userRoleMenuVoList);
        page.setRecords(pageList);

        return page;
    }

    @Override
    public Integer myUpdateById(User user) {
        userMapper.myUpdateById(user);
        return null;
    }

    @Override
    @Transactional

    public void saveWithRoles(UserVo user) {
        userMapper.insert(user);
        tjUserroleMapper.delete(new QueryWrapper<TjUserrole>().eq("userid", user.getId()));
        for(Role role : user.getRoleList()){
            TjUserrole tjUserrole = new TjUserrole();
            tjUserrole.setUserid(user.getId());
            tjUserrole.setRoleid(role.getRoleId());
            tjUserroleMapper.insert(tjUserrole);
        }
    }

    @Override
    @Transactional
    public void editWithRoles(UserVo user) {
        userMapper.updateByIdWithoutPassword(user);
        tjUserroleMapper.delete(new QueryWrapper<TjUserrole>().eq("userid", user.getId()));
        for(Role role : user.getRoleList()){
            TjUserrole tjUserrole = new TjUserrole();
            tjUserrole.setUserid(user.getId());
            tjUserrole.setRoleid(role.getRoleId());
            tjUserroleMapper.insert(tjUserrole);
        }

    }

    @Override
    public void changePassword(Long userId, String oldpassword, String newpassword) {
        String password = userMapper.selectById(userId).getPassword();
        if(!password.equals(oldpassword)){
            throw new WWException(WWExceptionEnum.ERROR_PASSWORD);
        }
        userMapper.updatePassword(userId, oldpassword, newpassword);
    }

    @Override
    @Transactional
    public void editWithRoles(UserDTO user) {
//        System.out.println("user is ------------------");
//        System.out.println(user);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        userMapper.updateByIdWithoutPassword(userVo);
//        tjUserroleMapper.delete(new QueryWrapper<TjUserrole>().eq("userid", user.getId()));
        for(Role role : user.getAllRoleList()){
            tjUserroleMapper.delete(new QueryWrapper<TjUserrole>().eq("userid", user.getId()).eq("roleid", role.getRoleId()));
        }
        for(Role role : user.getSelRoleList()){
            TjUserrole tjUserrole = new TjUserrole();
            tjUserrole.setUserid(user.getId());
            tjUserrole.setRoleid(role.getRoleId());
            tjUserroleMapper.insert(tjUserrole);
        }

    }

    @Override
    public boolean checkSameUserName(String userName) {
        if(userMapper.selectCount(new QueryWrapper<User>().eq("username", userName))>0){
            return true;
        }
        return false;
    }

    public boolean checkEditSameUserName(Long id, String userName) {
        if(userMapper.selectCount(new QueryWrapper<User>().eq("username", userName).ne("id", id))>0){
            return true;
        }
        return false;
    }
}




